package xy.web.util;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

public class Http {

	protected String filte(String html){
		html = html.replaceAll("\r", "");
		html = html.replaceAll("\n", "");

		html = html.replaceAll("<br/>", " ");
		html = html.replaceAll("<br>", " ");
		html = html.replaceAll("<BR/>", " ");
		html = html.replaceAll("<BR>", " ");
		html = html.replaceAll("&nbsp;", " ");
		html = html.replaceAll("	", " ");

		html = html.replaceAll("[ ]+", " ");
		html = html.replaceAll("[ ]>", ">");

		html = html.replaceAll("></", "> </");

		
		return html;
	}
	
	protected String sessionId = null;
	protected String send = "UTF-8";
	protected String rec = "UTF-8";
	protected int timeout = 30000;

	public Http() {

	}

	public Http(String send, String rec) {
		this.send = send;
		this.rec = rec;
	}

	public String getSessionId(){
		return this.sessionId;
	}
	public String get(String url, Object p) {
		return this.http(url, p, "GET");
	}

	public String post(String url, Object p) {
		return this.http(url, p, "POST");
	}

	protected String http(String urlStr, Object param, String method) {
		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		DataInputStream dis = null;
		ByteArrayOutputStream baos = null;
		URL url = null;

		try {
			String content = "";
			if(param instanceof String){
				content = (String)param;
			}else{
				Map mp = (Map)param;
				if (mp != null && mp.size() > 0) {
					Iterator it = mp.keySet().iterator();
					StringBuffer s = new StringBuffer("");
					while (it.hasNext()) {
						String name = it.next().toString();
						s.append("&").append(name).append("=");
						s.append(URLEncoder.encode(mp.get(name).toString(),
								this.send));
					}
					content = s.toString().substring(1);
				}
			}
 			if (method.toUpperCase().equals("GET")) {
				urlStr += (urlStr.indexOf("?") == -1 ? "?" : "&") + content;
			}

			url = new URL(urlStr);
			HttpURLConnection.setFollowRedirects(false);
			
			conn = (HttpURLConnection)url.openConnection();
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			conn.setRequestProperty("Content-Length", content.length()+"");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Cache-Control", "no-cache");
			conn.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
			conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
			
			if (sessionId != null) {
				conn.setRequestProperty("Cookie", sessionId);
			}
			conn.setConnectTimeout(timeout);
			conn.setRequestMethod(method.toUpperCase());
			
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			
			if (method.toUpperCase().equals("POST")) {
				dos = new DataOutputStream(conn.getOutputStream());
				dos.writeBytes(content);
				dos.flush();
			}
			
			if (sessionId == null) {
				String cookieValue = conn.getHeaderField("Set-Cookie");
				if(cookieValue!=null){
					sessionId = cookieValue.substring(0, cookieValue.indexOf(";"));
				}
			}
			
			if(conn.getResponseCode()==HttpURLConnection.HTTP_MOVED_TEMP){
				String location = conn.getHeaderField("Location");
				if(location!=null){
					return HttpURLConnection.HTTP_MOVED_TEMP+location;
				}
			}

			dis = new DataInputStream(conn.getInputStream());
			String encoding = rec;
			byte[] bytetemp = null;
			String html = null;
			int readlen = 0;
			byte[] buffer = new byte[1024];
			baos = new ByteArrayOutputStream();
			while (-1 != (readlen = dis.read(buffer))) {
				baos.write(buffer, 0, readlen);
			}
			bytetemp = baos.toByteArray();
			if (encoding == null || encoding.equals("")) {
				html = new String(bytetemp);
			} else {
				html = new String(bytetemp, encoding);
			}
			html = filte(html);
			
			return html.trim();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				dos.close();
			} catch (Exception e) {

			}

			try {
				baos.close();
			} catch (Exception e1) {

			}
			try {
				dis.close();
			} catch (Exception e) {

			}
			try{
				conn.disconnect();
			}catch(Exception e){
				
			}
		}
		return null;
	}
}
